/*
 * $Id: CARESRequestHandler.java,v 1.4 2012/04/24 01:48:10 navdeep_mahajan Exp $
 * 
 * Copyright (C) 2010 General Electric Company. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of the General
 * Electric Company (GE). You shall not disclose this software and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with GE.
 * 
 * GE MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 * NON-INFRINGEMENT. GE SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING, OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES.
 */
package com.ge.healthcare.autosc.createrfs;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.ge.healthcare.autosc.common.createrfs.RFSLogger;
import com.ge.healthcare.autosc.common.util.ApplicationInfo;
import com.ge.healthcare.autosc.common.util.PropertyConstants;
import com.ge.healthcare.autosc.createrfs.request.CreateRFSRequest;
import com.ge.healthcare.autosc.createrfs.response.CreateRFSResponse;
import com.ge.med.service.eds.commons.DataException;
import com.ge.med.service.eds.commons.ResourceException;
import com.ge.med.service.eds.rfs.IRFS;
import com.ge.med.service.eds.rfs.ObjectFactory;
import com.ge.med.service.eds.rfs.vo.RFSCreateCARES;
import com.ge.med.service.eds.rfs.vo.RFSResponse;
import com.ge.med.service.eds.rfs.vo.RFSResponseCARES;
import com.ge.med.service.eds.rfs.vo.RFSTechLogDetails;

/**
 * Handler for CreateRFSRequest messages.
 * 
 */
public class CARESRequestHandler {
	private static final String FAILED = "FAILED";
	private static final String OK = "OK";

	public CreateRFSResponse handle(Object object) {
		CreateRFSResponse resp = null;

		CreateRFSRequest request = (CreateRFSRequest) object;

		String symptom = request.getSymptom1() + " " + request.getSymptom2();
		try {
			IRFS iRFS = ObjectFactory.getInstance().getRFSObject();
			RFSCreateCARES vo = new RFSCreateCARES();
			// Set the same values as used by PPADS
			vo.setFEExpedite("N");
			vo.setISCExpedite("N");
			vo.setAlertStat("N");
			vo.setTecAssigned(null);
			vo.setRfsQueueName("V");
			vo.setMagnetSw("Y");
			vo.setInsiteAssignedFlag("Y");
			vo.setAuthorizedBy("autosc");
			vo.setContactName("Proactive Service");
			vo.setCustomerAuthorizesOvertime("N");
			vo.setCustomerInitiatedCall("N");
			vo.setEquipmentStatus("CS");
			vo.setEquipmentStatusDate(new SimpleDateFormat("yyyyMMdd")
					.format(new Date()));
			vo.setEquipmentStatusTime(new SimpleDateFormat("HHmm")
					.format(new Date()));
			vo.setFeOnSiteFlag("N");
			vo.setLegalEntityCode("000");
			vo.setRfsNote("Created by Digital Services");
			vo.setServiceType("MON");
			// Service class of 93 is missing
			// vo.setServiceClass("93");
			vo.setSymptom(symptom);
			vo.setSystemId(request.getSystemid());

			RFSResponseCARES response = null;
			try {
				RFSLogger.info(this.getClass(), "handle", "Request:" + vo);
				// create the Cares request
				response = (RFSResponseCARES) iRFS.create(vo);
				RFSLogger.info(this.getClass(), "handle", "Received Response:"
						+ response);
				// if a valid response is there, proceed to update the techlogs,
				// else in case of an exception create a Failure response
				try {
					RFSTechLogDetails techLogDetails = new RFSTechLogDetails();
					// set the rfs number obtained from the cares rfs response
					// and other values required by techlog object
					techLogDetails.setRFSNumber(response.getRFSNumber());
					techLogDetails.setTechLogComments(this
							.buildURLForTechLog(request.getSystemid()));
					techLogDetails.setSystemId(request.getSystemid());
					techLogDetails.setOperatorBadge("00000");
					techLogDetails.setAddUpdateSwitch("A");
					techLogDetails.setDate("");
					techLogDetails.setTime("");
					RFSLogger.info(this.getClass(), "handle",
							"Updating Tech Logs:" + techLogDetails);
					RFSResponse updtResponse = iRFS
							.updateTechLog(techLogDetails);
					RFSLogger.info(this.getClass(), "handle",
							"Tech Logs update response:" + updtResponse);
					// if techlog is updated, create a OK response, else in case
					// of an exception create a response with status set to
					// Partial
					resp = new CreateRFSResponse(response.getRFSNumber(), null,
							OK, null);
				} catch (ResourceException e) {
					e.printStackTrace();
					RFSLogger
							.fatal(this.getClass(),
									"resource exception caught while updating CARES techlog in handle",
									e);
					resp = new CreateRFSResponse(response.getRFSNumber(), null,
							OK, e.getMessage());
				} catch (DataException e) {
					e.printStackTrace();
					RFSLogger
							.fatal(this.getClass(),
									"data exception caught while updating CARES techlog in handle",
									e);
					resp = new CreateRFSResponse(response.getRFSNumber(), null,
							OK, e.getMessage());
				} catch (Exception e) {
					// handle the case when request generates successfully but
					// techlog updation fails
					RFSLogger.fatal(this.getClass(), "handle", e);
					resp = new CreateRFSResponse(response.getRFSNumber(), null,
							OK, e.getMessage());
				}

			} catch (ResourceException e) {
				e.printStackTrace();
				RFSLogger
						.fatal(this.getClass(),
								"resource exception caught while creating CARES RFS in handle",
								e);
				resp = new CreateRFSResponse(null, null, FAILED, e.getMessage());
			} catch (DataException e) {
				e.printStackTrace();
				RFSLogger
						.fatal(this.getClass(),
								"data exception caught while creating CARES RFS in handle",
								e);
				resp = new CreateRFSResponse(null, null, FAILED, e.getMessage());
			} catch (Exception e) {
				// handle the case, when request generation fails
				RFSLogger.fatal(this.getClass(), "handle", e);
				resp = new CreateRFSResponse(null, null, FAILED, e.getMessage());
			}

		}

		catch (Exception e) {
			RFSLogger.fatal(this.getClass(), "handle", e);
			resp = new CreateRFSResponse(null, null, FAILED, e.getMessage());
		}
		return resp;
	}

	/**
	 * Builds the dragon URL for tech logs
	 * 
	 * @return
	 */
	public String buildURLForTechLog(String systemId) {
		 String asdURL = ApplicationInfo.getInstance().getProperty(
		 PropertyConstants.ASD_WEB_INTERFACE_URL);
		asdURL = asdURL.replaceAll("<SYSTEM_ID>", systemId);
		String scriptStart = "<script>";
		String scriptEnd = "\";</script>\n";
		int maxLen = 33;
		StringBuffer outputBuff = new StringBuffer();

		outputBuff.append("<div id='dragon' style='position:relative'>\n");
		outputBuff.append(scriptStart)
				.append("var u=\"TECHNICAL SUMMARY: <a href='")
				.append(scriptEnd);

		while (asdURL.length() > 0) {
			if (asdURL.length() >= maxLen) {
				outputBuff.append(scriptStart).append("u+=\"")
						.append(asdURL.substring(0, maxLen)).append(scriptEnd);
				asdURL = asdURL.substring(maxLen);
			} else {
				outputBuff.append(scriptStart).append("u+=\"").append(asdURL)
						.append(scriptEnd);
				asdURL = "";
			}
		}
		outputBuff.append(scriptStart).append("u+=\"' target='_blank'")
				.append(scriptEnd);
		outputBuff.append(scriptStart).append("u+=\">MDEX Dragon Tool</a>")
				.append(scriptEnd);
		outputBuff.append(scriptStart)
				.append("this.dragon.innerHTML=u;</script></div>")
				.append("</script>\n");

		String output = outputBuff.toString();
		return output;
	}
}
